import {Component, OnInit} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CopyUtil} from '../../../utils/copy.util';
import {StatusEnum} from '../../../core/enum/status.enum';
import {FilterEnum, FilterTypeEnum} from '../../../core/enum/filter.enum';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {OtherUtil} from '../../../utils/other.util';
import {BigscreenManageService} from './bigscreen-manage.service';
import {HTTP_BASE_URL, SERVERS_NAME} from '../../../config/config';
import {SourceServer} from '../../../common/source.server';
import {Observable, Observer} from 'rxjs';
import {StorageUtil} from '../../../utils/storage.util';

@Component({
  selector: 'app-bigscreen-manage',
  templateUrl: './bigscreen-manage.component.html',
  styleUrls: ['./bigscreen-manage.component.scss'],
  providers: [BigscreenManageService, SourceServer]
})
export class BigscreenManageComponent implements OnInit {

  searchLabel = '';
  zlStatus = null;
  pageInfo: PageEntity = new PageEntity();
  allList = [];
  displayList = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  isAllCheck = false;
  isIndeterminate = false;

  isAdd = true;
  isFirst = true;
  showAddModal = false; // 新增弹框
  oneObj: DicObj = new DicObj();
  validateForm: FormGroup;
  canDelete = true;

  allTypes = [
    {
      text: '优秀学生风采',
      value: 0
    }, {
      text: '精品课程',
      value: 1
    }, {
      text: '历年获奖',
      value: 2
    }];
  zlStatusList = [{text: '启用', value: '1'}, {text: '未启用', value: '0'}];

  // 默认图片
  previewVisibleMoren = false;
  fileList = [];
  // 上传文件地址
  previewImage: string | undefined = '';
  previewVisible = false;
  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true
  };
  uploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;
  headerInfo = null;
  linkInfo = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}`;

  showLokkModal = false; // 查看弹框
  lookObj: DicObj = new DicObj();

  constructor(
    private service: BigscreenManageService,
    private message: NzMessageService,
    private fb: FormBuilder,
    private sourceServer: SourceServer,
  ) {
  }

  ngOnInit() {
    this.headerInfo = StorageUtil.getFileHeader();
    this.getPage();
    this.initForm();
  }

  initForm() {
    this.validateForm = this.fb.group({
      materialTitle: [null, [Validators.required]],
      category: [null, [Validators.required]],
      sort: [null, [Validators.required]],
      addr: [null, []],
      materialDes: [null, []]
    });
  }

  /**
   * 分页过滤逻辑搜索处理
   * @param pageConfig:当前分页对象
   * @param currVal:前端传入值
   * @param acceptVal:后台接受字段
   * @param mode:匹配没模式
   * @param type:搜索类型
   */
  dealComFilterLogic(pageConfig: PageEntity, currVal: any, acceptVal: any, mode: any, type: any): void {
    pageConfig.filters[acceptVal.toString()] = currVal ? {
      matchMode: mode,
      value: currVal,
      whereType: type
    } : undefined;

  }

  // 点击查询
  clickSearch() {
    this.pageInfo.first = 1;
    this.dealComFilterLogic(this.pageInfo, this.searchLabel, 'materialTitle', FilterEnum.CONTAINS, FilterTypeEnum.AND);
    this.dealComFilterLogic(this.pageInfo, this.zlStatus, 'status', FilterEnum.EQUALS, FilterTypeEnum.AND);
    this.getPage();
  }

  // 点击重置
  resetSearch() {
    this.pageInfo.first = 1;
    this.searchLabel = null;
    this.zlStatus = null;
    delete this.pageInfo.filters['materialTitle'.toString()];
    delete this.pageInfo.filters['status'.toString()];
    this.getPage();
  }

  // 分页查询
  getPage() {
    this.service.page(this.pageInfo).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
      }
    });
  }

  // 第几页
  searchPageIndex(event) {
    this.pageInfo.first = event;
    this.getPage();
  }

  // 每页几条
  searchPageSize(event) {
    this.pageInfo.rows = event;
    this.pageInfo.first = 1;
    this.getPage();
  }

  currentPageDataChange($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }

  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  checkDelete(): void {
    if (OtherUtil.deleteIds(this.mapOfCheckedId).length > 0) {
      this.canDelete = false;
    } else {
      this.canDelete = true;
    }
  }

  checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  /**
   * 姓名，学号，班级搜索
   * @param filed 字段：姓名，学号，班级
   * @param value 输入的值
   */
  titleSearch(filed: string, value: string): void {
    this.pageInfo.first = 1;
    this.dealComFilterLogic(this.pageInfo, value, filed, FilterEnum.CONTAINS, FilterTypeEnum.AND);
    this.getPage();
  }

  /**
   * 重置
   * @param field 字段
   */
  resetFilter(field: string): void {
    this.pageInfo.first = 1;
    delete this.pageInfo.filters[field];
    this.getPage();
  }

  // 表格过滤
  filterSome(event, flag) {
    let val = null;
    switch (event) {
      case 0:
        val = '优秀学生风采';
        break;
      case 1:
        val = '精品课程';
        break;
      case 2:
        val = '历年获奖';
        break;
    }
    this.pageInfo.first = 1;
    this.dealComFilterLogic(this.pageInfo, val, flag, FilterEnum.EQUALS, FilterTypeEnum.AND);
    this.getPage();
  }

  // 点击删除一个
  deleteOne(id) {
    this.service.deletes([id]).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.getPage();
      }
    });
  }

  // 批量操作 1：删除，2：启用，3：撤回
  opreatAll(type) {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    let opt = null;
    let text = '';
    if (type === 1) {
      opt = 'deletes';
      text = '删除';
    } else if (type === 2) {
      opt = 'enables';
      text = '启用';
    } else {
      opt = 'disables';
      text = '撤销';
    }
    if (arr.length < 1) {
      this.message.warning('请勾选要' + text + ' 的数据!');
      return;
    }
    this.service[opt](arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.mapOfCheckedId = {};
        this.pageInfo.first = 1;
        this.getPage();
      } else {
        this.message.warning(res.message);
      }
    });
  }

  cancelFn(): void {
    this.canDelete = true;
    this.isAllCheck = false;
    this.mapOfCheckedId = {};
    this.isIndeterminate = false;
  }

  // 点击新增
  clickAdd() {
    this.initForm();
    this.isAdd = true;
    this.isFirst = false;
    this.fileList = [];
    this.oneObj = new DicObj();
    this.showAddModal = true;
  }

  dealAddSub(): void {
    this.service.create(this.oneObj).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.showAddModal = false;
        this.getPage();
      }
    });
  }

  dealEditSub(): void {
    this.service.update(this.oneObj).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.showAddModal = false;
        this.getPage();
      }
    });
  }

  // 新增确认
  handleOk() {
    if (this.fileList.length <= 0) {
      this.message.warning('上传文件不能为空!');
      return;
    }
    if (this.oneObj.category === '优秀学生风采') {
      if (!this.oneObj.materialDes) {
        this.message.warning('展示板块为优秀学生风采时，资料描述不能为空!');
        return;
      }
    }
    if (this.oneObj.category === '校外实训基地') {
      if (!this.oneObj.materialDes) {
        this.message.warning('展示板块为校外实训基地时，资料描述不能为空!');
        return;
      }
      if (!this.oneObj.addr) {
        this.message.warning('展示板块为校外实训基地时，地址不能为空!');
        return;
      }
    }
    if (this.oneObj.category === '精品课程') {
      this.oneObj.dataType = 2;
    } else {
      this.oneObj.dataType = 1;
    }
    this.oneObj.materialId = this.fileList[0].uid;
    this.oneObj.status = 0;
    this.isAdd ? this.dealAddSub() : this.dealEditSub();
  }

  // 点击编辑
  editUse(data) {
    this.fileList = [];
    this.isAdd = false;
    this.isFirst = true;
    this.service.view(data.id).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.oneObj = CopyUtil.deepCopy(res.datas, {});
        if (this.oneObj.materialVO) {
          const files = this.oneObj.materialVO;
          files['uid'.toString()] = this.oneObj.materialId;
          files['name'.toString()] = this.oneObj.materialVO.fileOriginalName;
          files['status'.toString()] = 'done';
          files['url'.toString()] = this.linkInfo + 'source/view/'
            + this.oneObj.materialVO.moduleName + '/' + this.oneObj.materialVO.fileNewName;
          this.fileList.push(files);
        }
        this.showAddModal = true;
      }
    });
  }

  // 点击启用
  openUse(obj) {
    this.service.enables([obj.id]).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.getPage();
      } else {
        this.message.warning(res.message);
      }
    });
  }

  // 点击撤回
  closeUse(obj) {
    this.service.disables([obj.id]).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.getPage();
      } else {
        this.message.warning(res.message);
      }
    });
  }

  cateChange(event) {
    if (event && !this.isFirst) {
      this.fileList = [];
      this.oneObj.materialDes = null;
    } else {
      this.isFirst = false;
    }
  }

  beforeUpload = (file: File) => {
    const that = this;
    return new Observable((observer: Observer<boolean>) => {
      let flag;
      if (that.oneObj.category === '精品课程') { // 视频
        flag = (file.type === 'audio/mp4') || (file.type === 'video/mp4');
      } else { // 图片
        flag = (file.type === 'image/jpeg') || (file.type === 'image/jpg') || (file.type === 'image/png');
      }
      if (!flag) {
        this.message.warning('优秀学生风采和历年获奖板块只能上传图片，精品课程板块只能上传视频!');
        observer.complete();
        return;
      }
      observer.next(flag);
      observer.complete();
    });
  }

  /**
   * 上传
   */
  getUploadInfo(event) {
    const {file, fileList, type} = event;
    if (type === 'success') {
      if (file.response.status === StatusEnum.SUCCESS) {
        fileList.forEach((item) => {
          if (item.response) {
            const datas = item.response.datas;
            item.uid = datas.id;
            item.url = this.linkInfo + 'source/view/' + datas.moduleName + '/' + datas.fileNewName;
          }
        });
        this.fileList = fileList;
      } else {
        this.message.warning('文件上传失败,请重新上传!');
        this.fileList = [];
      }
    } else if (type === 'error') {
      this.fileList = [];
    }
  }

  /**
   * 删除上传资源
   * @param file s
   */
  deleteFlile = (file: UploadFile) => {
    this.fileList.forEach((item, index) => {
      if (item.uid === file.uid) {
        // 调用后台删除图片
        this.fileList.splice(index, 1);
        this.sourceServer.deleteFile([file.uid]).subscribe(res => {
          if (res.status === StatusEnum.SUCCESS) {
            this.message.success('文件删除成功!');
          }
        });
      }
    });
  }

  /*查看资料*/
  lookUse(data) {
    this.lookObj = new DicObj();
    this.service.view(data.id).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.lookObj = res.datas;
        this.showLokkModal = true;
      }
    });
  }

  openUrl() {
    window.open(this.linkInfo + 'source/view/' + this.lookObj.materialVO.moduleName + '/' + this.lookObj.materialVO.fileNewName);
  }
}

class DicObj {
  materialTitle?: string;
  id?: string;
  category?: string;
  sort?: number;
  materialId?: string;
  materialDes?: string;
  addr?: string;
  dataType?: number;
  status?: number;
  materialVO?: any;
}

